﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.System.Menu
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysMenuRepository : Repository<SysMenu, DefaultDbContext>
    {
        private readonly ILogger logger;

        public SysMenuRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<SysMenuRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        /// <summary>
        /// 更新菜单显示状态
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="isVisible"></param>
        /// <returns></returns>
        public bool UpdateMenuVisible(SysMenu menu, bool isVisible)
        {
            if (menu == null)
                return false;
            var sql_update = Sql.Builder;
            sql_update.Append("Update sys_menu SET is_visible = @0 where menu_id = @1", isVisible, menu.MenuId);//局部更新数据库
            int affectCount = DbContext.Execute(sql_update);
            if (affectCount > 0)
            {
                menu.IsVisible = isVisible;
                base.OnUpdated(menu);//更新内存数据
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取用户的菜单集合
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        //public IEnumerable<SysMenu> GetUserMenus(int userId)
        //{
        //    return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
        //    {
        //        return UserMenusCacheKey(userId);
        //    }, () =>
        //    {
        //        Sql sql = Sql.Builder.Select("sys_menu.menu_id").From("sys_menu")
        //        .InnerJoin("sys_role_menu").On("sys_menu.menu_id=sys_role_menu.menu_id")
        //        .InnerJoin("sys_user_role").On("sys_user_role.role_id=sys_role_menu.role_id")
        //        .InnerJoin("sys_role").On("sys_role.role_id=sys_user_role.role_id")
        //        .Where("sys_user_role.user_id=@0", userId)
        //        .Where("sys_menu.is_visible=1 AND sys_role.status=1");
        //        return sql;
        //    });
        //}

        private string UserMenusCacheKey(int userId)
        {
            return $"UserMenus:{userId}";
        }
    }
}